<template>
    <el-card shadow="never" class="border-0">
        <el-row :gutter="20">
            <el-col :span="12">
                <!-- 搜索 -->
                <el-form :model="searchForm" label-width="80px" class="mb-3">
                    <el-row :gutter="20">
                        <el-col :span="8" :offset="0">
                            <el-form-item label="用户名">
                                <el-input v-model="searchForm.username" placeholder="用户名" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="手机号">
                                <el-input v-model="searchForm.phone" placeholder="手机号" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <div class="flex items-center justify-end">
                                <el-button type="primary" @click="initData">搜索</el-button>
                                <el-button @click="resetSearchForm">重置</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>

                <div>全部人员</div>
                <el-table 
                    ref="multipleTableRef" 
                    :data="tableData" 
                    v-loading="tableDataLoading" 
                    @row-click="handleSelectionChange"
                    style="width: 100%"
                    border 
                    height="250">
                    <el-table-column label="用户名" width="100" align="center">
                        <template #default="{ row }">
                        {{ row.username }}
                        </template>
                    </el-table-column>
                    <el-table-column label="角色" align="center">
                        <template #default="{ row }">
                        {{ formatRoleName(row.roleId) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="手机号" align="center">
                        <template #default="{ row }">
                        {{ row.phone }}
                        </template>
                    </el-table-column>
                    <el-table-column label="邮箱" width="250" align="center">
                        <template #default="{ row }">
                        {{ row.email }}
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 分页组件 -->
                <el-pagination 
                    @current-change="initData" 
                    :current-page="currentPage" 
                    :page-size="limit"
                    layout="prev, pager, next" 
                    :total="total">
                </el-pagination>
            </el-col>

            <el-col :span="12">
                <el-form label-width="80px" class="mb-3">
                    <el-row :gutter="20">
                        <el-col :span="20">
                            <el-form-item label="已选择" style="display:block;">
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <div>选中人员（{{ selectApprovalPerson.length }}）</div>
                <el-table 
                    :data="selectApprovalPerson" 
                    style="width: 100%" 
                    border 
                    height="250">
                    <el-table-column type="index" label="序号" width="100" align="center" />
                    <el-table-column label="用户名" width="80" align="center">
                        <template #default="{ row }">
                        {{ row.username }}
                        </template>
                    </el-table-column>
                    <el-table-column label="角色" align="center">
                        <template #default="{ row }">
                        {{ formatRoleName(row.roleId) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="手机号" align="center">
                        <template #default="{ row }">
                        {{ row.phone }}
                        </template>
                    </el-table-column>
                    <el-table-column label="邮箱" width="200" align="center">
                        <template #default="{ row }">
                        {{ row.email }}
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="80" align="center">
                        <template #default="scope">
                            <el-button type="primary" size="small" text @click="removeSelectedUser(scope.row)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </el-card>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getRoleList } from "~/api/role";
import { getApprovalPersonList,getApprovalPersonByIds } from "~/api/manager";

//define props
const props = defineProps({
    ids: {
        type: Array,
        default: []
    }
})

const multipleTableRef = ref()
const tableData = ref([]) // 列表数据
const selectApprovalPerson = ref([]) // 选中的人员

const roles = ref([])
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableDataLoading = ref(false)

const searchForm = reactive({
    username: "",
    phone: "",
    page: currentPage.value,
    size: limit.value,
})

// 重置搜索框
const resetSearchForm = () => {
  searchForm.username = ""
  searchForm.phone = ""
  initData()
}

// 当选择项发生变化时会触发该事件
function handleSelectionChange(row) {
    //console.log("select点击事件:",JSON.stringify(row))
    if(row && row.id != 0){
        const bool = selectApprovalPerson.value.some(user => user.id === row.id) // 存在返回true 否则返回false
        if (!bool) {
            // 不存在则添加
            selectApprovalPerson.value.push(row)
        }
        //console.log("selectApprovalPerson.value:",JSON.stringify(selectApprovalPerson.value))
    }
    //计算ids
    getCheckedApprovalPerson()
}

// 移除已选择用户
function removeSelectedUser(row){
    //console.log("移除用户:",JSON.stringify(row))
    selectApprovalPerson.value = selectApprovalPerson.value.filter(user => user.id != row.id)
    //计算ids
    getCheckedApprovalPerson()
}

// 生命周期
onMounted(() => {
    //初始化角色字典数据
    getRoleList().then(res => {
        if(res){
            roles.value = res.records.filter(function(item) {
                return item.name != "engineer" && item.name != "companyManager";
            });
        }
    })

    //加载已选择用户
    initSelectedData()

    //加载表格数据
    initData()
})

//加载已选择用户
function initSelectedData(){
    //console.log("ids:",JSON.stringify(props.ids))
    if(props.ids && props.ids.length>0){
        let paramIo = {}
        paramIo.ids = props.ids
        getApprovalPersonByIds(paramIo)
            .then(res => {
            if(res){
                selectApprovalPerson.value = res
            }else{
                selectApprovalPerson.value = []
            }
        })
    }
}

//获取列表数据
function initData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }
    tableDataLoading.value = true
    searchForm.page = currentPage.value
    getApprovalPersonList(currentPage.value,searchForm)
        .then(res => {
        if(res && res.records){
            tableData.value = res.records
            total.value = res.total
        }else{
            tableData.value = []
            total.value = 0
        }
    })
    .finally(() => {
        tableDataLoading.value = false
    })
}

//角色字典数据，数据转换方法
const formatRoleName = (roleId) => {
  return roles.value.find(x => x.id == roleId)?.description || roleId
}

// 对外暴露方法
const emit = defineEmits([
    'getCheckedApprovalPerson',
])

/**
 * 获取选择的审核人的id集合
 */
const getCheckedApprovalPerson = () => {
    const selectData = selectApprovalPerson.value
    //有数据
    if(selectData && selectData.length > 0){
        const ids = selectData.map(user => {
            return user.id;
        });
        //console.log('return approval person ids: ', JSON.stringify(ids))
        emit("getCheckedApprovalPerson", ids)
    }else{
        //无数据
        emit("getCheckedApprovalPerson", [])
    }
}
</script>
